<template>
  <el-dialog
    title="分配权限"
    :visible.sync="visible"
    width="50%"
    :before-close="handlerClose"
  >
    <el-tree
      v-if="visible"
      ref="tree"
      node-key="id"
      show-checkbox
      check-strictly
      default-expand-all
      :data="list"
      :default-checked-keys="checkedList"
      :props="defaultProps"
    >
    </el-tree>
    <div slot="footer">
      <el-button @click="handlerClose">取 消</el-button>
      <el-button type="primary" @click="onConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPermissionApi } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleInfoById, assignPmsApi } from '@/api/setting'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [], // 存放树形控件数据
      checkedList: [], // 存放默认选中数据
      defaultProps: {
        // 指定显示名称的字段
        label: 'name'
      },
      roleId: ''
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 获取角色详情数据
    async getRoleDetail(id) {
      this.roleId = id
      const { permIds } = await getRoleInfoById(id)
      this.checkedList = permIds
    },
    // 点击确认按钮，分配权限
    async onConfirm() {
      console.log(this.$refs.tree.getCheckedNodes())
      const permIds = this.$refs.tree.getCheckedNodes().map((item) => item.id)
      const data = {
        id: this.roleId,
        permIds
      }
      await assignPmsApi(data)
      this.$message.success('操作成功')
      this.handlerClose()
    },
    // 初始化属性控件的数据
    async initData() {
      const res = await getPermissionApi()
      this.list = tranListToTreeData(res, '0')
    },
    // 处理弹框关闭逻辑
    handlerClose() {
      this.checkedList = []
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style>
</style>